package com.github.jlib.javafx.samples.systemtray;

import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;
import javafx.application.Platform;
import javafx.stage.Stage;

public class FxSystemTray {

    private static final boolean SUPPORTED = SystemTray.isSupported();

    public static void create(Stage stage, String tooltip, String iconUrl) {
        create(stage, tooltip, iconUrl, defaultPopupMenu(stage, tooltip), defaultMouseListener(stage));
    }

    public static void create(Stage stage, String tooltip, String iconUrl, PopupMenu popup, MouseListener listener) {
        if (!SUPPORTED) {
            return;
        }
        // 关闭窗口隐藏不退出
        Platform.setImplicitExit(false);
        stage.setOnCloseRequest(e -> hide(stage));
        // 创建托盘图标，让图片自动缩放以适应图标大小
        URL url = FxSystemTray.class.getResource(iconUrl);
        TrayIcon icon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(url), tooltip, popup);
        icon.setImageAutoSize(true);
        // 为托盘图标添加鼠标点击事件
        if (null != listener) {
            icon.addMouseListener(listener);
        }
        // 添加托盘图标到系统托盘中
        try {
            SystemTray.getSystemTray().add(icon);
        } catch (AWTException ex) {}
    }

    private static void hide(Stage stage) {
        Platform.runLater(() -> {
            if (SUPPORTED) {
                stage.hide();
            } else {
                System.exit(0);
            }
        });
    }

    private static void show(Stage stage) {
        Platform.runLater(() -> {
            if (stage.isIconified()) {
                stage.setIconified(false);
            }
            stage.show();
            stage.toFront();
        });
    }

    private static MouseListener defaultMouseListener(Stage stage) {
        return new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (MouseEvent.BUTTON1 == e.getButton()) {
                    show(stage);
                }
            }
        };
    }

    private static PopupMenu defaultPopupMenu(Stage stage, String name) {
        MenuItem menuExit = new MenuItem("退出" + name);
        menuExit.addActionListener(e -> System.exit(0));
        MenuItem menuShow = new MenuItem("打开" + name);
        menuShow.addActionListener(e -> show(stage));
        PopupMenu popup = new PopupMenu();
        popup.add(menuShow);
        popup.add(menuExit);
        return popup;
    }

}
